<?php

namespace app\store\controller\content;

use app\store\controller\Controller;
use app\store\model\Ad as AdModel;
use app\store\model\Article as ArticleModel;

/**
 * 广告管理控制器
 * Class article
 * @package app\store\controller\content
 */
class Ad extends Controller
{
    /**
     * 广告列表
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $model = new AdModel;
        $list = $model->getList();
        return $this->fetch('index', compact('list'));
    }

    /**
     * 添加广告
     * @return array|mixed
     */
    public function add()
    {
        $model = new AdModel;
        if (!$this->request->isAjax()) {
            $list = ArticleModel::field('article_id,article_title')->select();
            return $this->fetch('add',compact('list'));
        }
        // 新增记录
        if ($model->add($this->postData('ad'))) {
            return $this->renderSuccess('添加成功', url('content.ad/index'));
        }
        return $this->renderError($model->getError() ?: '添加失败');
    }

    /**
     * 更新广告
     * @param $ad_id
     * @return array|mixed
     * @throws \think\exception\DbException
     */
    public function edit($advert_id)
    {
        // 文章广告
        $model = AdModel::where('advert_id',$advert_id)->find();
        if (!$this->request->isAjax()) {
            $list = ArticleModel::field('article_id,article_title')->select();
            return $this->fetch('edit', compact('model','list'));
        }
        // 更新记录
        if ($model->edit($this->postData('ad'))) {
            return $this->renderSuccess('更新成功', url('content.ad/index'));
        }
        return $this->renderError($model->getError() ?: '更新失败');
    }

    /**
     * 删除广告
     * @param $advert_id
     * @return array
     * @throws \think\exception\DbException
     */
    public function delete($advert_id)
    {
        // 文章广告
        $model = AdModel::where('advert_id',$advert_id)->find();
        if (!$model->delete()) {
            return $this->renderError( '删除失败');
        }
        return $this->renderSuccess('删除成功');
    }

}